--
-- Author: shunguo.chen
-- Date: 2018-11-07 18:50:41
--
-- TeamMatchView 组队查找器
--

local TabsBtn = require("app.widget.TabsBtn")
local ListViewExtend = require("app.widget.ListViewExtend")

local NewRareInfoView = require("app.newBag.views.NewRareInfoView")
local TeamTargetPanel = import(".TeamTargetPanel")

local TeamTargetFirstRender = import(".renders.TeamTargetFirstRender")
local TeamTargetSecondRender = import(".renders.TeamTargetSecondRender")
local TeamTargetThirdRender = import(".renders.TeamTargetThirdRender")
local TeamTargetSecretRender = import(".renders.TeamTargetSecretRender")

local fileName = string.getModeName(...)
local ClassRef = class(fileName, app.mvc.ViewBase)

local PANEL_NUM = 4

ClassRef.VIEW_ROOT_RES = Res.TeamMatchScene

function ClassRef:init()
    self._ui.Button_close:addClickEventListener(function()
        executeFunc(self._onCloseView, self)
    end)

    -- tabsBtn --
    local panelTab = self._ui.Panel_tab
    local btns = {}
    local tabsBtnInitPosYAry = {}
    for i=1,PANEL_NUM do
        local btn = panelTab:getChildByName("selected_btn_" .. i)
        btn:setVisible(true)
        tabsBtnInitPosYAry[i] = btn:getPositionY()
        btns[i] = btn
    end
    self._tabsBtnInitPosYAry = tabsBtnInitPosYAry

    local function onTabsBtn(index)
        if self._curIdx then
            self._curIdx = index
            self:switchPanel()
        else
            self._curIdx = index
        end
    end
    self._tabsBtn = TabsBtn.new(btns, onTabsBtn, 1)

    -- luck panel -- 暂时不用了
    self._ui.Panel_luck:setVisible(false)
    display.uiAddClick(self._ui.Panel_luck, function()
        self:_showRareInfo()
    end)

    -- menu --
    self._menuList = ListViewExtend.scrollToItemExtend(self._ui.ListView)
    self._secretMenu = nil
    self._speedMenu = nil
    self._firstMenuCaches = {}
    self._firstMenuRenders = {}
    self._secondMenuCaches = {}
    self._secondMenuRenders = {}
    self._thirdMenuCaches = {}
    self._thirdMenuRenders = {}
    
    -- teamTarget panel
    self._targetPanel = TeamTargetPanel.create(self._ui.node_seek)
end

-- idx 第几个matchType
-- openParams {true,true,true,false} matchType开放情况
-- openParams[idx] 必定是true
function ClassRef:show(idx, openParams)
    self:setVisible(true)

    -- 按是否开放，排列TabsBtn
    local posIdx = 0
    for i,v in ipairs(openParams) do
        local btn = self._tabsBtn:getBtn(i)
        if v then 
            posIdx = posIdx + 1
        end
        btn:setVisible(v)
        btn:setPositionY(self._tabsBtnInitPosYAry[posIdx])
    end

    self:switchPanel(idx)
end

function ClassRef:onOperate(cb)
    self.super.onOperate(self, cb)

    self._targetPanel:onOperate(cb)
end

function ClassRef:switchPanel(idx)
    if idx then 
        self._curIdx = idx
        self._tabsBtn:setSelected(idx)
    end
    executeFunc(self._onOperate, "switchPanel", self._curIdx)
end

function ClassRef:getTargetPanel()
    return self._targetPanel
end

function ClassRef:refreshTarget(target)
    if self._curTarget == target then return end

    -- print("refreshTarget", target:getName(), target.id)
    self._curTarget = target

    self._targetPanel:setData(target)
    executeFunc(self._onOperate, "selectTarget", target)

    self:checkGuide()
end

function ClassRef:updateAutoApplyStatus()
    self._targetPanel:updateAutoApplyStatus()

    for i,render in ipairs(self._thirdMenuRenders) do
        render:refreshAutoApply()
    end
    for i,render in ipairs(self._secondMenuRenders) do
        render:refreshAutoApply()
    end
    for i,render in ipairs(self._firstMenuRenders) do
        render:refreshAutoApply()
    end
end

function ClassRef:updateAutoRecruitStatus()
    self._targetPanel:updateAutoRecruitStatus()

    for i,render in ipairs(self._thirdMenuRenders) do
        render:refreshAutoRecruit()
    end
    for i,render in ipairs(self._secondMenuRenders) do
        render:refreshAutoRecruit()
    end
    for i,render in ipairs(self._firstMenuRenders) do
        render:refreshAutoRecruit()
    end
end

function ClassRef:updateInCrossMatchStatus()
    for i,render in ipairs(self._thirdMenuRenders) do
        render:refreshInCrossMatch()
    end
    for i,render in ipairs(self._secondMenuRenders) do
        render:refreshInCrossMatch()
    end
    for i,render in ipairs(self._firstMenuRenders) do
        render:refreshInCrossMatch()
    end
end

function ClassRef:refreshApplyNew(b)
    self._targetPanel:refreshApplyNew(b)
end

-- team TeamVo
function ClassRef:refreshTeam(team)
    self._targetPanel:refreshTeam(team)
end

function ClassRef:refreshMember()
   self._targetPanel:refreshMember()
end

function ClassRef:refreshTeamList(teamList)
    self._targetPanel:refreshTeamList(teamList)
end

-- 刷新推荐队伍的申请状态
function ClassRef:refreshTeamListApply(team)
    self._targetPanel:refreshTeamListApply(team)
end

--------------------- MenuList start ------------------------
function ClassRef:remove()
    for i,render in ipairs(self._firstMenuCaches) do
        render:release()
    end
    for i,render in ipairs(self._firstMenuRenders) do
        render:release()
    end
    for i,render in ipairs(self._secondMenuCaches) do
        render:release()
    end
    for i,render in ipairs(self._secondMenuRenders) do
        render:release()
    end
    for i,render in ipairs(self._thirdMenuCaches) do
        render:release()
    end
    for i,render in ipairs(self._thirdMenuRenders) do
        render:release()
    end
    if self._secretMenu then
        self._secretMenu:release()
    end
    if self._speedMenu then
        self._speedMenu:release()
    end
    self._curFirstBtn = nil
    self._curSecondBtn = nil
    self._curThirdBtn = nil

    self._targetPanel:remove()
end

function ClassRef:_getFirstMenuRender()
    local render
    if #self._firstMenuCaches > 0 then
        render = table.remove(self._firstMenuCaches, 1)
    end
    if not render then
        render = TeamTargetFirstRender.create()
        render:retain()
        render:onBtnClick(handler(self, self._onFirstBtnClick))
    end
    self._firstMenuRenders[#self._firstMenuRenders + 1] = render
    return render
end
function ClassRef:_getSecondMenuRender()
    local render
    if #self._secondMenuCaches > 0 then
        render = table.remove(self._secondMenuCaches, 1)
    end
    if not render then
        render = TeamTargetSecondRender.create()
        render:retain()
        render:onBtnClick(handler(self, self._onSecondBtnClick))
    end
    self._secondMenuRenders[#self._secondMenuRenders + 1] = render
    return render
end
function ClassRef:_getThirdMenuRender()
    local render
    if #self._thirdMenuCaches > 0 then
        render = table.remove(self._thirdMenuCaches, 1)
    end
    if not render then
        render = TeamTargetThirdRender.create()
        render:retain()
        render:onBtnClick(handler(self, self._onThirdBtnClick))
    end
    self._thirdMenuRenders[#self._thirdMenuRenders + 1] = render
    return render
end
function ClassRef:_getSecretMenuRender()
    if not self._secretMenu then
        self._secretMenu = TeamTargetSecretRender.create()
        self._secretMenu:retain()
    end
    return self._secretMenu
end
function ClassRef:_getSpeedMenuRender()
    if not self._speedMenu then
        local node = cc.CSLoader:createNode(Res.TeamTargetSpeedNode)
        node:setContentSize(node:getChildByName("Panel"):getContentSize())
        node:retain()
        self._speedMenu = node
    end
    return self._speedMenu
end

function ClassRef:refreshMenu(targets, idxs)
    self._firstMenuCaches = table.attach(self._firstMenuCaches, self._firstMenuRenders)
    self._firstMenuRenders = {}
    self._secondMenuCaches = table.attach(self._secondMenuCaches, self._secondMenuRenders)
    self._secondMenuRenders = {}
    self._thirdMenuCaches = table.attach(self._thirdMenuCaches, self._thirdMenuRenders)
    self._thirdMenuRenders = {}
    self._curFirstBtn = nil
    self._curSecondBtn = nil
    self._curThirdBtn = nil

    self._targets = targets
    self._menuList:removeAllItems()

    for i,firstTarget in ipairs(targets) do
        local render = self:_getFirstMenuRender()
        render:setData(firstTarget)
        render:setSelected(i==idxs[1])
        self._menuList:pushBackCustomItem(render)
        if i==idxs[1] then
            self._curFirstBtn = render
            local secondTargets = firstTarget.curSubTargets
            local hasTarget = true
            if firstTarget.id == Enums.TeamTargetType.speed then
                self._menuList:pushBackCustomItem(self:_getSpeedMenuRender())
            elseif firstTarget.id == Enums.TeamTargetType.secret then
                hasTarget = false
                local secondRender = self:_getSecretMenuRender()
                secondRender:setData(secondTargets[1])
                self._curSecondBtn = secondRender
                self._menuList:pushBackCustomItem(secondRender)
            end

            if hasTarget then
                for j,secondTarget in ipairs(secondTargets) do
                    local secondRender = self:_getSecondMenuRender()
                    secondRender:setData(secondTarget)
                    secondRender:setSelected(j==idxs[2])
                    self._menuList:pushBackCustomItem(secondRender)
                    if j==idxs[2] then 
                        self._curSecondBtn = secondRender
                        if #idxs == 3 then
                            local thirdTargets = secondTarget.curSubTargets
                            for k,thirdTarget in ipairs(thirdTargets) do
                                local thirdRender = self:_getThirdMenuRender()
                                thirdRender:setData(thirdTarget)
                                thirdRender:setSelected(k==idxs[3])
                                self._menuList:pushBackCustomItem(thirdRender)
                                if k==idxs[3] then
                                    self._curThirdBtn = thirdRender
                                end
                            end
                        end
                    end
                end
            end
        end
    end

    local curSubTargets = targets[idxs[1]].curSubTargets
    local curTarget = curSubTargets[idxs[2]]
    if #idxs == 3 then
        curSubTargets = curTarget.curSubTargets
        curTarget = curSubTargets[idxs[3]]
    end
    self:refreshTarget(curTarget)
    self:_scrollMenuToTarget()
end

function ClassRef:_onFirstBtnClick(btn, isSelected, data)
    if self._curFirstBtn then
        -- 选择的是已经选中的，清空二／三级
        local btnIdx = table.indexof(self._firstMenuRenders, self._curFirstBtn)
        local startIdx = self._menuList:getIndex(self._curFirstBtn)
        local endIdx
        if btnIdx < #self._firstMenuRenders then
            endIdx = self._menuList:getIndex(self._firstMenuRenders[btnIdx+1])
        else
            endIdx = #self._menuList:getItems()
        end

        for i=1, endIdx-startIdx-1 do
            self._menuList:removeItem(startIdx+1)
        end

        self._secondMenuCaches = table.attach(self._secondMenuCaches, self._secondMenuRenders)
        self._secondMenuRenders = {}
        self._thirdMenuCaches = table.attach(self._thirdMenuCaches, self._thirdMenuRenders)
        self._thirdMenuRenders = {}

        self._curFirstBtn:setSelected(false)
        self._curFirstBtn = nil
        self._curSecondBtn = nil
        self._curThirdBtn = nil
    end

    if not isSelected then
        btn:setSelected(true)
        self._curFirstBtn = btn
        local firstTarget = data
        local secondTargets = firstTarget.curSubTargets
        local hasTarget = true
        local curIdx = self._menuList:getIndex(btn)

        if firstTarget.id == Enums.TeamTargetType.speed then
            curIdx = curIdx + 1
            self._menuList:insertCustomItem(self:_getSpeedMenuRender(), curIdx)
        elseif firstTarget.id == Enums.TeamTargetType.secret then
            hasTarget = false
            local secondRender = self:_getSecretMenuRender()
            secondRender:setData(secondTargets[1])
            curIdx = curIdx + 1
            self._menuList:insertCustomItem(secondRender, curIdx)
            self._curSecondBtn = secondRender
            self:refreshTarget(secondTargets[1])
        end

        if hasTarget then
            local isThreeLayer = (firstTarget.id == Enums.TeamTargetType.normal)
            isThreeLayer = isThreeLayer or (firstTarget.id == Enums.TeamTargetType.legion)
            local hasCurTarget = (firstTarget.id == self._curTarget.type)
            local secondIdx, thirdIdx = 1, 1
            if hasCurTarget then
                for i,secondTarget in ipairs(secondTargets) do
                    if isThreeLayer then
                        local thirdTargets = secondTarget.curSubTargets
                        local hasThirdTarget = false
                        for j,thirdTarget in ipairs(thirdTargets) do
                            if thirdTarget == self._curTarget then
                                thirdIdx = j
                                hasThirdTarget = true
                                break
                            end
                        end
                        if hasThirdTarget then
                            secondIdx = i
                        end
                    else
                        if secondTarget == self._curTarget then
                            secondIdx = i
                        end
                    end
                end
            end

            local curSecondRender, curThirdRender
            for i,secondTarget in ipairs(secondTargets) do
                local secondRender = self:_getSecondMenuRender()
                secondRender:setData(secondTarget)
                secondRender:setSelected(i == secondIdx)
                curIdx = curIdx + 1
                self._menuList:insertCustomItem(secondRender, curIdx)
                if i == secondIdx then
                    self._curSecondBtn = secondRender
                    if isThreeLayer then
                        local thirdTargets = secondTarget.curSubTargets
                        for j,thirdTarget in ipairs(thirdTargets) do
                            local thirdRender = self:_getThirdMenuRender()
                            thirdRender:setData(thirdTarget)
                            thirdRender:setSelected(j == thirdIdx)
                            curIdx = curIdx + 1
                            self._menuList:insertCustomItem(thirdRender, curIdx)
                            if j == thirdIdx then
                                self._curThirdBtn = thirdRender
                                self:refreshTarget(thirdTarget)
                            end
                        end
                    else
                        self:refreshTarget(secondTarget)
                    end
                end
            end
        end
    end
    self:_scrollMenuToTarget()
end
function ClassRef:_onSecondBtnClick(btn, isSelected, data)
    if data:isThreeLayer() then
        if self._curSecondBtn then
            -- 有三级菜单打开着，清除三级菜单
            self._curSecondBtn:setSelected(false)
            local preData = self._curSecondBtn:getData()
            local idx = self._menuList:getIndex(self._curSecondBtn)
            local thirdTargets = preData.curSubTargets
            self._thirdMenuCaches = table.attach(self._thirdMenuCaches, self._thirdMenuRenders)
            self._thirdMenuRenders = {}
            for i=#thirdTargets, 1, -1 do
                self._menuList:removeItem(idx + i)
            end

            self._curSecondBtn = nil
            self._curThirdBtn = nil
        end

        if not isSelected then
            btn:setSelected(true)
            self._curSecondBtn = btn
            local idx = self._menuList:getIndex(self._curSecondBtn)
            local thirdTargets = data.curSubTargets
            local curRender
            for i,thirdTarget in ipairs(thirdTargets) do
                local thirdRender = self:_getThirdMenuRender()
                thirdRender:setData(thirdTarget)
                thirdRender:setSelected(false)
                thirdRender:setVisible(true)
                self._menuList:insertCustomItem(thirdRender, idx + i)
                if thirdTarget == self._curTarget then
                    curRender = thirdRender
                end
            end

            if not curRender then
                curRender = self._thirdMenuRenders[1]
            end
            curRender:setSelected(true)
            self._curThirdBtn = curRender
            self:refreshTarget(curRender:getData())
        end
    else
        if not isSelected then
            if self._curSecondBtn then
                self._curSecondBtn:setSelected(false)
            end
            btn:setSelected(true)
            self._curSecondBtn = btn
            self:refreshTarget(data)
        end
    end

    self:_scrollMenuToTarget()
end
function ClassRef:_onThirdBtnClick(btn, isSelected, data)
    if not isSelected then
        if self._curThirdBtn then
            self._curThirdBtn:setSelected(false)
        end
        btn:setSelected(true)
        self._curThirdBtn = btn
        self:refreshTarget(data)
        self:_scrollMenuToTarget()
    end
end

function ClassRef:_scrollMenuToTarget()
    self._menuList:refreshView()
    self._menuList:performWithDelay(function()
        if cc.isAlive(self._curThirdBtn) then
            self._menuList:scrollToItem(self._curThirdBtn)
        elseif cc.isAlive(self._curSecondBtn) then
            self._menuList:scrollToItem(self._curSecondBtn)
        elseif cc.isAlive(self._curFirstBtn) then
            self._menuList:scrollToItem(self._curFirstBtn)
        else
            self._menuList:scrollToIndex(0)
        end
    end, 0)
end

--------------------- MenuList end -------------------------

--------------------- RareInfo start ------------------------
-- 展示上方宝物具体信息
function ClassRef:_showRareInfo()
    local conf = GD:queryRestrictedRewardShowById( 101 )
    if self._rareInfoPanel then
        self._rareInfoPanel:setData( conf )
    else
        self._rareInfoPanel = NewRareInfoView.create()
        self._rareInfoPanel:setData( conf )
        self:addChild( self._rareInfoPanel )

        -- 点击空白区域关闭
        display.nodeRemoveForNotHit(self._rareInfoPanel, function()
            if self._rareInfoPanel then
                self._rareInfoPanel:setVisible(false)
            end
        end)
    end

    self._rareInfoPanel:setVisible(true)
    local triggerNode = self._ui.Panel_luck
    local boundingBox = triggerNode:getBoundingBox()
    local worldPos = triggerNode:getParent():convertToWorldSpace( cc.p( boundingBox.x, boundingBox.y ) )
    boundingBox.x = worldPos.x
    boundingBox.y = worldPos.y
    display.adjustNodePos( boundingBox, self._rareInfoPanel )
end

-- 刷新上方好运符相关信息
function ClassRef:refreshLuckPanel()
    local _, usedToday = UD.player:getCharmUsedInfo()
    local canUsedToday = tonumber( GD:getSystemPar( "charmdailymaxcostamount" ) ) -- 今日可使用上限
    local str = (canUsedToday - usedToday) .. "/" .. canUsedToday 
    self._ui.Panel_luck:getChildByName( "num" ):setString(str)
end

--------------------- RareInfo end ------------------------


-- 检查是否触发了引导
function ClassRef:checkGuide()
    local funcId
    if self._curTarget:isSpeed() then
        funcId = Constant.FUNC_TYPE_TEAMMATCHING_SPEED
    elseif self._curTarget:isNormal() then
        funcId = Constant.FUNC_TYPE_TEAMMATCHING_TEAM
    elseif self._curTarget:isPvp() then
        funcId = Constant.FUNC_TYPE_TEAMMATCHING_PVP
    end

    if not funcId then return end

    local params = {
        scene = funcId,
        sceneSelf = self,
        getFunc = self.getGuideNodeFunc,
        nextFunc = self.checkGuide
    }
    EM:notify("checkGuide", params)
end

-- 获取引导node
function ClassRef:getGuideNodeFunc(id)
    return self._targetPanel:getGuideNodeFunc(id)
end

return ClassRef
